/*
 * This file is part of Catfish.
 * Copyright (C) 2010 Namazu Studios LLC
 * 
 * Catfish is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 * 
 * Catfish is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with Catfish.  If not, please visit:
 *  
 * http://www.gnu.org/licenses/
 *  
 */
package com.namazustudios.catfish.provider;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Provides default values for enum types. By default, it provides the zeroth
 * value. (EnumType.vaules()[0]); If it is an empty enum, it returns null.
 * 
 * @author patricktwohig
 * 
 */
public class EnumValueProvider implements ValueProvider<Enum<?>> {

	@Override
	public Enum<?> provide(Class<? extends Enum<?>> type) {
	    Method m= null;
	    boolean accessible = false;

		try {
		    Enum<?>[] values;

			m = type.getMethod("values");
            m.setAccessible(true);

			values = (Enum<?>[]) m.invoke(null);

			accessible = m.isAccessible();

			if (values.length > 0) {
				return values[0];
			} else {
				return null;
			}

		} catch (NoSuchMethodException ex) {
			throw new IllegalArgumentException(ex);
		} catch (IllegalArgumentException ex) {
			throw new IllegalArgumentException(ex);
		} catch (IllegalAccessException ex) {
			throw new IllegalArgumentException(ex);
		} catch (InvocationTargetException ex) {
			throw new IllegalArgumentException(ex);
		}finally {
		    if (m != null) {
		      m.setAccessible(accessible);
		    }
		}
	}

}
